package com.id.supaclean.utils

import android.Manifest
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.net.Uri
import android.text.format.Formatter
import androidx.core.content.ContextCompat
import com.id.supaclean.MyApplication.Companion.appContext
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*

const val TIMESTAMP_PATTERN_DATETIME = "yyyy-MM-dd HH:mm:ss"
const val TIMESTAMP_PATTERN_DATE = "yyyy-MM-dd"
const val TIMESTAMP_PATTERN_TIME = "HH:mm:ss"

/**
 * 将秒的时间戳转换为毫秒，若当前已经是毫秒则直接返回
 * 若当前的值不为毫秒也不为秒不进行转换直接返回；
 * @return 返回毫秒时间戳
 */
private fun Long.toTimeInMillis(): Long {
    val ctl = System.currentTimeMillis().toString().length
    val tl = toString().length
    return if (ctl != tl && ctl - 3 == tl) this * 1000 else this
}

fun Long.asTime(pattern: String = TIMESTAMP_PATTERN_DATETIME): String {
    val timestamp = toTimeInMillis()
    return SimpleDateFormat(pattern, Locale.CHINA).format(timestamp)
}

fun Float.toFixed(num: Int): Float = try {
    String.format("%.${num}f", this).toFloat()
} catch (e: Throwable) {
    0f
}

val df2 = DecimalFormat("0.00")

val df1 = DecimalFormat("0.0")

val hasReadStoragePermission
    get() = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
val hasWriteStoragePermission
    get() = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)

fun checkSelfPermission(permission: String): Boolean {
    return ContextCompat.checkSelfPermission(appContext, permission) == PackageManager.PERMISSION_GRANTED
}


fun smartChangeUint(size: Long):String {
    if (size / (1024*1024*1024) > 0)  {
        return "GB"
    } else if (size / (1024*1024) > 0) {
        return "MB"
    }else if (size / 1024 > 0) {
        return "KB"
    } else {
        return "B"
    }
}

inline fun <reified T> String.formatJson(): T {
    if (T::class.java == String::class.java) return this as T
    val typeToken = object : TypeToken<T>() {}.type
    return Gson().fromJson(this, typeToken)
}

fun caculate(unit: String,size:Long):String {
    when (unit) {
        "GB" -> {
            return df2.format(size / (1024 * 1024*1024).toFloat())
        }
        "MB" ->{
            return df2.format(size/(1024*1024).toFloat())
        }
        "KB" -> {
            return df2.format((size/1024).toFloat())
        }
        else -> return "0.00"
    }
}


private fun getMemory(type: String): Float {
    val am = appContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    val mi = ActivityManager.MemoryInfo()
    am.getMemoryInfo(mi)
    return try {
        if (type == "availMem") {
            Formatter.formatFileSize(appContext, mi.availMem)
        } else {
            Formatter.formatFileSize(appContext, mi.totalMem)
        }.run {
            replace("GB", "").trim().toFloat()
        }
    } catch (e: Throwable) {
        0f
    }
}

fun hasPermission(permission: String) = ContextCompat.checkSelfPermission(
    appContext, permission
) == PackageManager.PERMISSION_GRANTED


//获取仅出现在桌面上的app
fun getLauncherApps(): List<ResolveInfo> {
    val intent = Intent()
    intent.addCategory(Intent.CATEGORY_LAUNCHER)
    intent.action = Intent.ACTION_MAIN
    return appContext.packageManager.queryIntentActivities(intent, 0)
}

fun startGooglePlay() {
    val intent = Intent(Intent.ACTION_VIEW)
    intent.data = Uri.parse("market://details?id=" + appContext.packageName)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    //存在手机里没安装应用市场的情况，跳转会包异常，做一个接收判断
    //存在手机里没安装应用市场的情况，跳转会包异常，做一个接收判断
    if (intent.resolveActivity(appContext.packageManager) != null) {
        appContext.startActivity(intent)
    } else {
        intent.data =
            Uri.parse("https://play.google.com/store/apps/details?id=" + appContext.packageName)
        if (intent.resolveActivity(appContext.packageManager) != null) {
            appContext.startActivity(intent)
        }
    }
}